

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;




public class Server {

    public static String getRootDir() {
        return "root";
    }


    public static void main(String[] arg) throws Exception{
        User.init();
        int port;
        if(arg.length>0)
            port = Integer.parseInt(arg[0]);
        else
            port = 21;
        System.out.printf("Starting a server on port %d\n",port);
        new AcceptConnections(port).start();
        BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
        while(true){
            System.out.print(">>");
            String input = keyboard.readLine();
            if(input.equals("exit"))
                System.exit(1);
            else if(input.equals("create user")) {
                System.out.println("What is the user name?");
                String name = keyboard.readLine();
                if(User.get(name) != null) {
                    System.out.println("That username already exist.");
                    continue;
                }

                System.out.println("What is the user password?");
                String pwd = keyboard.readLine();
                if(User.writeUser(new User(name,pwd)));
                    System.out.println("User created successfully");
            } else if(input.equals("list users")) {
                User.printUsers();
                
            } else if(input.equals("delete user")) {
                System.out.println("what is the user name?");
                User.deleteUser(keyboard.readLine());
                System.out.println("user deleted");

                

            } else if(input.equals("help")) {
                System.out.println("Available commands:");
                System.out.println("exit");
                System.out.println("create user");
                System.out.println("list users");
                System.out.println("delete user");
            } else {
                System.out.println("Invalid Command");
            }
        }
    }
}

class AcceptConnections extends Thread{

    public AcceptConnections(int port) {
        this.port = port;
    }

    public void run() {
        ServerSocket serverSocket = null;
        
        try
            {serverSocket = new ServerSocket(port);}
        catch(Exception e)
            {System.out.printf("Could not start server in port %d. Shuting down server.\n",port);
            System.exit(1);}

        while(true) {
            try 
                {new Thread(new PI(serverSocket.accept())).start();}
            catch(Exception e)
                {System.out.println("Error acception incoming connection..."+e);}
        }
    }
    int port;
}
